package com.example.demo.controller;

import com.baidu.bas.core.constant.EruptRestPath;
import com.baidu.bas.core.service.IEruptDataService;
import com.baidu.bas.core.view.EruptApiModel;
import com.deepzero.mmma.channel.SendResult;
import com.example.demo.service.TryService;
import com.example.demo.vo.tyy.News;
import com.example.demo.vo.tyy.Template;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * 测试发送
 * @author liuzhenchuan@foxmail.com
 * @date 2021/1/6
 */
@RestController
@RequestMapping(EruptRestPath.ERUPT_API + "/try_send/")
@Slf4j
public class Try {

    @Resource
    private TryService tryService;

    @Resource
    private IEruptDataService iEruptDataService;

    @GetMapping(value = {"/wechat_users/{accountId}"})
    @ResponseBody
    public EruptApiModel wechatUsers(@PathVariable Long accountId) {
        Optional<List<WxMpUser>> opt =  tryService.wxUsers(accountId);
        if(opt.isPresent()){
            return EruptApiModel.successApi(opt.get());
        }else{
            return EruptApiModel.errorApi(EruptApiModel.Status.NOT_FOUND);
        }

    }

    @PostMapping(value = {"/sms"})
    @ResponseBody
    public EruptApiModel sms(@RequestBody Template template) {
        SendResult result = tryService.sendSms(template.getAccountId(),Long.parseLong(template.getTemplateId()),
                template.getToUser(),template.getVars());
        return toEruptApiModel(result);

    }

    private EruptApiModel toEruptApiModel(SendResult result) {
        if(result.isSuccess()){
            return EruptApiModel.successApi();
        }else{
            return EruptApiModel.errorApi("[" + result.getCode() + "]" + result.getInfo());
        }
    }

    @PostMapping(value = {"/wechat_template"})
    @ResponseBody
    public EruptApiModel wechatTemplate(@RequestBody Template template) {
        SendResult result = tryService.sendWeixinTemplate(template.getAccountId(),template.getTemplateId(),
                template.getToUser(),template.getVars());
        return toEruptApiModel(result);
    }

    @PostMapping(value = {"/wechat_48h_news"})
    @ResponseBody
    public EruptApiModel wechat48hNews(@RequestBody News news) {
        SendResult result = tryService.sendWeixinReply(news.getAccountId(),news.getNews(),
                news.getToUser(),news.getVars());
        return toEruptApiModel(result);
    }

}
